/*
 * @Author: sxb
 * @Email: sxb@mail.com
 * @Date: 2020-02-24 08:49:11
 * @Descripttion: 
 */

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators, ValidatorFn, AbstractControl } from '@angular/forms';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { PurchaseManageService } from '../purchase-manage/purchase-manage.service';
import { MaterialRelationService } from '../../basedata-manage/material-relation/material-relation.service';
import { ReturnproductManageService } from './returnproduct-manage.service';
import { HCommonService } from 'src/app/h-common/h-common.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';

export function whsAreaValidator(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
      const forbidden = nameRe.test(control.value);
      return forbidden ? null : {'whsAreaValidator': {value: control.value}};
  };
}

@Component({
  selector: 'app-returnproduct-manage',
  templateUrl: './returnproduct-manage.component.html',
  styleUrls: ['./returnproduct-manage.component.scss']
})
export class ReturnproductManageComponent implements OnInit {
  returnchangeRoles = {};
  returnchangeDetailRoles = {};
  poRoles = {};

  searchOrderCode: string = "";
  searchCode: string = "";
  searchName: string = "";
  bizType: any = "";
  InspectionStatus: any = "";

  editDisabled: boolean = true;
  RturnDisabled: boolean = true;
  ReplaceDisabled: boolean = true;// 换货请验
  ConfirmReturnDisabled: boolean = true;// 确认退货
  ConfirmReplaceDisabled: boolean = true;// 确认换货
  showReplace: boolean = false;
  showConfirmReplace: boolean = false;
  showConfirmReturn: boolean = false;

// 绑定下拉采购订单号数据 start
  poCode: any = '';
  BusinessType: any = "";
  selPoList = [{value:'',text:"请选择"}];
  bizTypeChange(data){
    this.handleSearch();
  }
  InspectionStatusChange(data){
    this.handleSearch();
  }
// 绑定下拉采购订单号数据 end
  
// 创建单据 start
  isVisible = false;
  isOkLoading = false;
  //创建单据
  add() {
    this.isVisible = true;

    this.poCode = '';
    this.BusinessType = '';
    this.getReceiveInfosByPo({page:this.pageIndexAdd,size:this.pagesizeAdd});
  }
  handleOk() {
    let data = {lstReceiveInfos:[], pocode: this.poCode, returntype: this.BusinessType};
    //let notExistNum = false;
    this.listDataAdd.forEach(item => {
      if(item.checked){
        if(item['outNumber'] == ''){
          //notExistNum = true;
          return;
        }else{
          data.lstReceiveInfos.push({id:item['id'], returnnum: item['outNumber'], returnDesc: item['outDesc']})
        }
      }
    });
    if (data.lstReceiveInfos.length < 1) {
      this.message.warning("请勾选物料并填写退货数量！");
      return;
    }
    if(this.BusinessType == ''){
      this.message.warning("请选择业务类型！");
      return;
    }
    if(this.poCode == ''){
      this.message.warning("请选择采购订单号！");
      return;
    }
    console.log(JSON.stringify(data));
    this.returnproductService.postCreatelist(data).subscribe(res=>{      
      this.handleSearch();
      this.isVisible = false;
    });
  }
  // 取消按钮
  handleCancel(): void {
    this.isVisible = false;
  }
// 创建单据 end

// 采购订单主列表 start
  listData = [];
  pageIndex: any = 0;//提交的页码
  pagesize: any = 10;//table每页条数
  totalSize: any = 2;//总共条数
  /* 分页切换 */
  clickPage(pageIndex) {
    this.pageIndex = pageIndex
    this.handleSearch()
  }
  //搜索
  handleSearch() {
    let data = {
      pocode: this.searchOrderCode,
      materialCode: this.searchCode,
      materialName: this.searchName,
      returntype: this.bizType,
      checkStatus: this.InspectionStatus,
      page: this.pageIndex - 1,
      size: this.pagesize,
      sort:"createDate,desc"
    };
    this.getReturnChange(data);
  }
  chkRetuanItem = null;
  checkSingle(data){
    if(this.chkRetuanItem != null){
      if(!data.checked || (data.checked && this.chkRetuanItem.id != data.id)){
        this.RturnDisabled = true;
        this.ReplaceDisabled = true;// 换货请验
        this.ConfirmReturnDisabled = true;// 确认退货
        this.ConfirmReplaceDisabled = true;// 确认换货
        
        this.showReplace = false;
        this.showConfirmReplace = false;
        this.showConfirmReturn = false;
      }
    }
    this.listData.forEach(item => {
      if(item.id !== data.id){ item.checked = false; }
    })
    this.chkRetuanItem = data.checked ? data : null;
    if(this.chkRetuanItem != null){
      this.getReturnChangeDetail({foid:data.id, page:0, size: this.detailPagesize})
    }else{
      this.detailListData = [];
    }
  }
// 采购订单主列表 end

// 采购订单详细列表 start
  detailListData = [];
  detailPageIndex: any = 0;//提交的页码
  detailPagesize: any = 10;//table每页条数
  detailTotalSize: any = 2;//总共条数
  /* 分页切换 */
  detailClickPage(pageIndex) {
    this.detailPageIndex = pageIndex - 1
  }
  // detailListData = [
  //   { kf: '11', checked: false }, 
  //   { kf: '223', checked: false }
  // ];
  chkDetailReturnItem = null;
  checkSingleDetail(data) {
    if(this.chkRetuanItem != null){
      if(this.chkRetuanItem.returntype == 0){
        this.showConfirmReturn = true;
        this.showReplace = false;
        this.showConfirmReplace = false;
      }
      else if(this.chkRetuanItem.returntype == 1){
        if(data.isCheck){
          this.showConfirmReturn = false;
          this.showReplace = true;
          this.showConfirmReplace = true;
        }else{
          this.showConfirmReturn = false;
          this.showReplace = false;
          this.showConfirmReplace = true;
        }
      }
    }
    this.detailListData.forEach(item => {
      if(item.kf !== data.kf){ item.checked = false; }
    })
    this.chkDetailReturnItem = data.checked ? data : null;
    //var e = this.detailListData.filter(s => s.checked);
    //if (e.length === 1) { this.editDisabled = false; } else { this.editDisabled = true; }
    if (this.chkDetailReturnItem == null) {
      this.RturnDisabled = true;
      this.ConfirmReturnDisabled = true;
      this.ConfirmReplaceDisabled = true;
      this.ReplaceDisabled = true;
    } else {
      this.RturnDisabled = false;
      this.ConfirmReturnDisabled = false;
      this.ConfirmReplaceDisabled = false;
      this.ReplaceDisabled = false;
    }
  }
// 采购订单详细列表 end

// 创建单据列表 start
  isAllCheckedAdd = false;
  pageIndexAdd: any = 0;//提交的页码
  pagesizeAdd: any = 6;//table每页条数
  totalSizeAdd: any = 2;//总共条数
  /* 分页切换 */
  clickPageAdd(pageIndex) {
    this.pageIndexAdd = pageIndex - 1
    this.handleSearchAdd()
  }
  handleSearchAdd() {
    let data = {page:this.pageIndexAdd,size:this.pagesizeAdd};
    this.getReceiveInfosByPo(data);
  }
  listDataAdd = [
    { kf: '11', checked: false }, 
    { kf: '223', checked: false }
  ];
  
  checkAllAdd(value: boolean): void {
    this.listDataAdd.forEach(item => {
      item.checked = value;
    })
  }
  checkSingleAdd(): void{
    let _isAllCheck = true;
    this.listDataAdd.forEach(item => {
      if(!item.checked){
        _isAllCheck = false;
      }
    })
    this.isAllCheckedAdd = _isAllCheck;
  }
  addOrderChange(value: string): void {
    let data = {pocode:value,page:0,size:this.pagesizeAdd};
    this.getReceiveInfosByPo(data);
  }
// 创建单据列表 end

// model 5 start

returnnum: number = 0;
returnDesc: string = '';
isShowBox5: boolean = false;
// showBox5(data) {
//   this.isShowBox5 = true;
// }
cancelBox5() {
  this.isShowBox5 = false;
}
okBox5() {
  let data = this.chkDetailReturnItem;
  data.returnnum = this.returnnum;
  data.returnDesc = this.returnDesc;
  this.putReturnChangeDetail(data, 0);
}

// model 5 end

// 修改详情 start
hidWarehouseId = '';
hidWhsAreaId = '';
isAltDatailVisible = false;
selWhsTree = [];

validateDetailForm: FormGroup;

//修改详情
showAltDetailVisible(data) {
  if(data == null){
    this.validateDetailForm.reset();  
    this.hidWarehouseId = '';
    this.hidWhsAreaId = '';
  }else{
    if (data.returnstatus == 0) {
      this.isShowBox5 = true;
      this.returnnum = data.returnnum;
      this.returnDesc = data.returnDesc;
    } else {
      this.isAltDatailVisible = true;        
      this.validateDetailForm.patchValue({
        id: data.id,
        txtPdData: data.produceDate,
        txtAdData: data.arrivalDate,
        txtSupplierBatch: data.providerBatch,
        txtCodeBatch: data.barcodeBatch,
        txtPackNumber: data.packageNumber,
        txtPackSpec: data.packSpec,
        txtWeight: data.returnnum,
        txtCheckWeight1: data.spotweight1,
        selMaterialWhsArea: data.warehouseId +"-"+ data.warehouseAreaId,
        txtCheckWeight2: data.spotweight2
      })
      this.hidWarehouseId = data.warehouseId;
      this.hidWhsAreaId = data.warehouseAreaId;
    }
    this.chkDetailReturnItem = data;
  }
}
altDetailOk() {
  var ef = this.listDataAdd;
  var w = this.BusinessType;
  console.log(ef.length);
  for (const i in this.validateDetailForm.controls) {
    this.validateDetailForm.controls[i].markAsDirty();
    this.validateDetailForm.controls[i].updateValueAndValidity();
  }
  if (this.validateDetailForm.status == "VALID") {
    let data = {
      id: this.chkDetailReturnItem.id,
      foid: this.chkRetuanItem.id,
      produceDate:this.formatDate(this.validateDetailForm.get('txtPdData').value),
      arrivalDate:this.formatDate(this.validateDetailForm.get('txtAdData').value),
      providerBatch:this.validateDetailForm.get('txtSupplierBatch').value,
      barcodeBatch:this.validateDetailForm.get('txtCodeBatch').value,
      packageNumber:this.validateDetailForm.get('txtPackNumber').value,
      packSpec:this.validateDetailForm.get('txtPackSpec').value,
      returnnum:this.validateDetailForm.get('txtWeight').value,
      spotweight1:this.validateDetailForm.get('txtCheckWeight1').value,
      spotweight2:this.validateDetailForm.get('txtCheckWeight2').value,
      warehouseId:this.hidWarehouseId,
      warehouseAreaId:this.hidWhsAreaId
    };
    this.putReturnChangeDetail(data, 1);
  }
}
// 取消按钮
altDetailCancel(): void {
  this.isAltDatailVisible = false;
}

// 修改详情 end

// modal 1 start
boxType: number = 1;
isShowBox1: boolean = false;
radioValue = '';
checkFirstMsg = '';
isAnxious = 0;
chkDetailId = '';// 选中详情ID

handleReplace() {
  let isExistCheckItem = false;
  this.detailListData.forEach(item=>{
    if(item.checked === true){
      isExistCheckItem = true;
      this.chkDetailId = item.id;
    }
  });
  if(isExistCheckItem){
    this.isShowBox1 = true;
    this.boxType = this.boxType == 1 ? 2 : 1;
    this.PurchaseManageService.getCheckFirst(this.chkRetuanItem.id).subscribe(res=>{
      this.checkFirstMsg = res;
    });
  }else{
    this.message.warning("请选择一条入库详细信息！");
  }
}
cancelBox1() {
  this.isShowBox1 = false
}
okBox1() {
  this.isOkLoading = true;
  setTimeout(() => {
    this.isOkLoading = false;
  }, 1000);
  let data = {
    id: this.chkDetailId,
    isexpedited: this.isAnxious
  };
  this.returnproductService.putCheckstCorage(data).subscribe(res => {
    this.isShowBox1 = false;
    this.isOkLoading = false;
    this.getReturnChangeDetail({foid:this.chkRetuanItem.id, page:0, size: this.detailPagesize})
  })
}
// modal 1 end

// modal 2 start
isShowBox2: boolean = false;
aryRaw = [];
aryPack = [];
materialOptions = [
  {
    label: '是否提供送货单',
    value: 'isdeliverylist'
  },
  {
    label: '是否提供COA',
    value: 'iscoa'
  },
  {
    label: '包装数据是否正确',
    value: 'isdatacorrect'
  },
  {
    label: '标签信息是否完整',
    value: 'iscompletetag'
  },
  {
    label: '外包装是否变形或破损',
    value: 'isdamaged'
  }
];
packageStatus = [
  {
    label:'是否提供送货单',
    value:'pcgisdeliverylist'
  },
  {
    label:'包装数是否正确',
    value:'pcgisdatacorrect'
  },
  {
    label:'外包装是否变形或破损',
    value:'pcgisdamaged'
  },
  {
    label:'尺寸误差是否在范围内',
    value:'pcgissizerange'
  },
  {
    label:'颜色是否正确',
    value:'pciscolorcorrect'
  },
  {
    label:'印刷内容是否完整清晰',
    value:'pcgiscompleteprinted'
  }
]
handleConfRetAndRep() {
  let isExistCheckItem = false;
  this.detailListData.forEach(item=>{
    if(item.checked === true){
      isExistCheckItem = true;
      this.chkDetailId = item.id;
    }
  });
  if(!isExistCheckItem){
    this.message.warning("请选择一条入库详细信息！");
  }else{
    this.isShowBox2 = true;
  }
}
cancelBox2() {
  this.isShowBox2 = false
}
okBox2() {
  let aryAll = this.aryRaw.concat(this.aryPack);
  let data = {
    id: this.chkDetailId,
    iscoa: aryAll.indexOf("iscoa") > -1 ? 1 : 0,
    iscompletetag: aryAll.indexOf("iscompletetag") > -1 ? 1 : 0,
    isdamaged: aryAll.indexOf("isdamaged") > -1 ? 1 : 0,
    isdatacorrect: aryAll.indexOf("isdatacorrect") > -1 ? 1 : 0,
    isdeliverylist: aryAll.indexOf("isdeliverylist") > -1 ? 1 : 0,
    pcgiscompleteprinted: aryAll.indexOf("pcgiscompleteprinted") > -1 ? 1 : 0,
    pcgisdamaged: aryAll.indexOf("pcgisdamaged") > -1 ? 1 : 0,
    pcgisdatacorrect: aryAll.indexOf("pcgisdatacorrect") > -1 ? 1 : 0,
    pcgisdeliverylist: aryAll.indexOf("pcgisdeliverylist") > -1 ? 1 : 0,
    pcgissizerange: aryAll.indexOf("pcgissizerange") > -1 ? 1 : 0,
    pciscolorcorrect: aryAll.indexOf("pciscolorcorrect") > -1 ? 1 : 0
  };
  this.returnproductService.postConfirmstorage(data).subscribe(res => {
    this.isShowBox2 = false;
    this.getReturnChangeDetail({foid:this.chkRetuanItem.id, page:0, size: this.detailPagesize})
  })
}
materialChecked(data) {
  this.aryRaw = data;
}
packageChecked(data){
  this.aryPack = data;
}
// modal 2 end

// model 3 start

isShowBox3: boolean = false;
handleReturnDetail() {
  let isExistCheckItem = false;
  this.detailListData.forEach(item=>{
    if(item.checked === true){
      isExistCheckItem = true;
      this.chkDetailId = item.id;
    }
  });
  if(!isExistCheckItem){
    this.message.warning("请选择一条入库详细信息！");
  }else{
    if(this.chkDetailReturnItem.inStatus === 1){
      this.message.warning("该数据已入库，请勿重复操作！");
    }else{
      this.isShowBox3 = true;
    }
  }
}
cancelBox3() {
  this.isShowBox3 = false;
}
okBox3() {
  let data = {
    id: this.chkDetailReturnItem.id
  };
  this.returnproductService.putBackDetail(data).subscribe(res => {
    this.isShowBox3 = false;
    this.getReturnChangeDetail({foid:this.chkRetuanItem.id, page:0, size: this.detailPagesize})
  })
}

// model 3 end

// model 4 start

isShowBox4: boolean = false;
delType: number = 0;
showBox4(data, type) {
  this.delType = type;
  switch (type) {
    case 1://1删除主表
      this.chkRetuanItem = data;
      break;
    case 2://1删除详情
    this.chkDetailReturnItem = data;
      break;
  }
  this.isShowBox4 = true;
}
cancelBox4() {
  this.isShowBox4 = false;
}
okBox4() {
  if(this.delType == 1){
    this.delReturnchange(this.chkRetuanItem);
  }else if(this.delType == 2){
    this.delReturnChangeDetail(this.chkDetailReturnItem);
  }
}

// model 4 end

  //修改
  edit() {
  }

  // 获取左侧树状结构
  getNodes() {
    this.relationService.getWhsTree().subscribe(res => {
      var newList = res;
      for (let i = 0; i < newList.length; i++) {
          newList[i] = {
              key: newList[i].id,
              title: newList[i].name,
              isLeaf: newList[i].warehouseAreas.length > 0 ? false : true,
              children: newList[i].warehouseAreas || []
          }
          if (newList[i].children && newList[i].children != '') {
              let children1 = newList[i].children
              for (let a = 0; a < children1.length; a++) {
                  children1[a] = {
                      key: newList[i].key + "-" + children1[a].id,
                      pId: newList[i].key,
                      pName: newList[i].title,
                      title: children1[a].name,
                      isLeaf: true
                  }
              }
          }
      }
      this.selWhsTree = newList;
    })
  }

  getAllPocodes(){
    this.returnproductService.getAllPocodes().subscribe(res => {
      let selList = [];
      res.forEach(element => {
        selList.push({value:element, text: element});
      });
      this.selPoList = this.selPoList.concat(selList);
    });
  }

  getReceiveInfosByPo(data){
    this.returnproductService.getReceiveInfosByPo(data).subscribe(res =>{
      res.content.forEach(item => {
        item.checked = false;
        item.outNumber = '';
        item.outDesc = '';
    })
    this.totalSizeAdd = res.totalElements
    this.listDataAdd = res.content;
    });
  }

  postCreatelist(data, callback){
    this.returnproductService.postCreatelist(data).subscribe(res=>{
      if (callback) {
        callback();
      }
    });
  }

  getReturnChange(data){
    this.returnproductService.getReturnChange(data).subscribe(res=>{
      res.content.forEach(item => {
      item.checked = false;
      })
      this.totalSize = res.totalElements
      this.listData = res.content;
      this.detailListData = [];
    });
  }

  getReturnChangeDetail(data){
    this.returnproductService.getReturnChangeDetail(data).subscribe(res=>{
      res.content.forEach(item => {
      item.checked = false;
      })
      this.detailTotalSize = res.totalElements;
      this.detailListData = res.content;
    });
  }

  delReturnchange(data){
    this.returnproductService.delReturnchange({id:data.id}).subscribe(res=>{
      this.isShowBox4 = false;
      this.detailListData = [];
      this.getReturnChange({page:this.pageIndex, size: this.pagesize})
    });
  }

  putReturnChangeDetail(data, type){
    this.returnproductService.putReturnChangeDetail(data).subscribe(res => {
      this.getReturnChangeDetail({foid:data.foid, page:0, size: this.detailPagesize})
      if (type == 0) {
        this.isShowBox5 = false;
      } else {
        this.isAltDatailVisible = false;
      }
      this.chkDetailReturnItem = null;
    })
  }  

  delReturnChangeDetail(data){
    this.returnproductService.delReturnChangeDetail({id:data.id}).subscribe(res => {
        this.getReturnChangeDetail({foid:data.id, page:0, size: this.detailPagesize});
        this.isShowBox4 = false;
    })
  }
  
  // 时间格式化
  formatDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd HH:mm:ss');
  }

  constructor(
    private PurchaseManageService: PurchaseManageService,
    private modal: NzModalService,
    private relationService : MaterialRelationService,
    private message: NzMessageService,
    private fb: FormBuilder,
    private commonService : HCommonService,
    private returnproductService : ReturnproductManageService,
    private datePipe: DatePipe
  ) { }

  ngOnInit(): void {
    /* 获取权限 */
    this.returnchangeRoles = this.commonService.getRoles("returnchange");
    this.returnchangeDetailRoles = this.commonService.getRoles("returnchangeDetail");
    this.poRoles = this.commonService.getRoles("po");

    this.validateDetailForm = this.fb.group({
      txtPdData: [null, [Validators.required]],
      txtAdData: [null, [Validators.required]],
      txtSupplierBatch: [null, [Validators.required]],
      txtCodeBatch: [null, [Validators.required]],
      txtPackNumber: [null, [Validators.required]],
      txtPackSpec: [null, [Validators.required]],
      txtWeight: [null, [Validators.required]],
      txtCheckWeight1: [null],
      selMaterialWhsArea: [null, [Validators.required, whsAreaValidator(/^\d+-\d+$/)]],
      txtCheckWeight2: [null]
    })
    this.getReturnChange({page:this.pageIndex, size: this.pagesize, sort:"createDate,desc"})
    this.getAllPocodes();
    this.getReceiveInfosByPo({page:this.pageIndexAdd,size:this.pagesizeAdd});
    this.getNodes();
  }
}
